export default function () {
    var oemcartIsWebp = "";
    function checkWebpFeature(feature, callback) {
        if (typeof oemcartIsWebp === "boolean") {
            return callback(feature, oemcartIsWebp);
        }

        var kTestImages = {
            lossy: "UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",
            lossless: "UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==",
            alpha: "UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA=="
        };
        var img = new Image();
        img.onload = function () {
            oemcartIsWebp = img.width > 0 && img.height > 0;
            callback(feature, oemcartIsWebp);
        };
        img.onerror = function () {
            oemcartIsWebp = false;
            callback(feature, false);
        };
        img.src = "data:image/webp;base64," + kTestImages[feature];
    }

    //获取屏幕像素密度
    const ratio = window.devicePixelRatio;
    var lazyImgs = [];

    //获取图片配置
    function getStoreConfigImageConfig() {
        if (!window.storeConfig || !window.storeConfig.imagerocket) {
            return false;
        }
        // php返回为对象字符串需转化
        return JSON.parse(window.storeConfig.imagerocket);
    }

    //图片转webp
    function getImageToWebP(suffix) {
        var config = getStoreConfigImageConfig();
        var webpSuffix = ["JPG", "JPEG", "PNG"];

        if (!config || config.status == 2 || !webpSuffix.includes(suffix)) {
            return "";
        }
        return `format,webp`;
    }

    //图片质量改变
    function getImageQuality(suffix) {
        var qualitySuffix = ["JPG", "JPEG", "WEBP"];
        //  || !qualitySuffix.includes(suffix)
        var config = getStoreConfigImageConfig();
        if (!config || config.status == 2 || (!getImageToWebP(suffix) && !qualitySuffix.includes(suffix))) {
            return "";
        }
        var quality = config.quality_type === 1 ? "q" : "Q";
        return `quality,${quality}_${config.quality_value}`;
    }

    // 加载图片
    function loadImg(option) {
        option.elment[0].onload = () => {
            moi.onEvent("lazyImg", option.imgSrc);
        };
        option.elment[0].onerror = () => {
            option.elment.attr("src", option.oldSrc);
        };

        var splitStr = option.imgSrc.indexOf("?") === -1 ? "?" : "&";
        var handleTypes = option.imgHandleTypes.filter(Boolean);
        var newSrc = option.src;
        if (handleTypes.length) {
            newSrc += splitStr + "x-oss-process=image/" + handleTypes.join("/");
        }
        option.elment.attr("src", newSrc);
    }

    function setImgUrl(elment) {
        // elment.attr("oem-if",true);

        //避免店匠导入的图片懒加载规则冲突
        if (elment.attr("data-aspect-ratio")) {
            return false;
        }

        var oldSrc = elment.attr("src");
        // 设置src属性:
        var imgSrc = elment.attr("data-src");
        //裁剪方法
        var cropType = elment.attr("data-crop-type");

        //裁剪高度
        var cropHeight = elment.attr("data-crop-height");

        //裁剪宽带
        var cropWidth = elment.attr("data-crop-width");

        //删除属性
        elment[0].removeAttribute("data-src");
        //如果有src属性加载src
        if (imgSrc) {
            // TODO 优化图片加载质量

            var fileExtension = imgSrc.substring(imgSrc.lastIndexOf(".") + 1).toUpperCase();
            var src = imgSrc;
            // oss支持裁剪的文件后缀名
            var whiteSuffix = ["JPG", "JPEG", "PNG", "BMP", "GIF", "TIFF", "WEBP"];

            // 图片处理格式
            var imgHandleTypes = [];
            if (whiteSuffix.includes(fileExtension)) {
                //默认宽度裁剪
                var width = cropWidth || elment.innerWidth();

                //高度裁剪
                if (cropType === "height") {
                    var height = cropHeight || elment.height();
                    if (height) {
                        imgHandleTypes.push(`resize,m_lfit,h_${Math.floor(width * (ratio > 1 ? ratio : 1.5))}`);
                    }
                } else {
                    if (width) {
                        imgHandleTypes.push(`resize,m_lfit,w_${Math.floor(width * (ratio > 1 ? ratio : 1.5))}`);
                    }
                }

                // 是否支持webp
                checkWebpFeature("lossy", function (feature, isSupported) {
                    if (isSupported) {
                        imgHandleTypes.push(getImageToWebP(fileExtension));
                    }
                    imgHandleTypes.push(getImageQuality(fileExtension));
                    loadImg({
                        src: src,
                        imgHandleTypes: imgHandleTypes,
                        imgSrc: imgSrc,
                        oldSrc: oldSrc,
                        elment: elment
                    });
                });
            } else {
                loadImg({
                    src: src,
                    imgHandleTypes: imgHandleTypes,
                    imgSrc: imgSrc,
                    oldSrc: oldSrc,
                    elment: elment
                });
            }
        }
    }

    //加载图片
    function lazyImageShow() {
        // 获取页面滚动的高度:
        const wtop = $(window).scrollTop();
        // 判断是否还有未加载的img:
        if (lazyImgs.length > 0) {
            // 获取可视区域高度:
            const wheight = $(window).height();
            const delIndexs = [];
            for (let i = 0; i < lazyImgs.length; i++) {
                const $i = lazyImgs[i];
                // 判断是否在可视范围内:
                if ($i.offset().top - wtop - 100 < wheight && $i.is(":visible")) {
                    delIndexs.push(i);
                    setImgUrl($i);
                }
            }

            for (let i = delIndexs.length - 1; i >= 0; i--) {
                lazyImgs.splice(delIndexs[i], 1);
            }
        }
    }

    const isSupportIntersectionObserver = window["IntersectionObserver"] ? true : false;
    let imgObserver = "";

    // 是否支持IntersectionObserver
    if (isSupportIntersectionObserver) {
        imgObserver = new IntersectionObserver(
            function (entrys) {
                for (const entry of entrys) {
                    if (entry.intersectionRatio > 0) {
                        const element = $(entry.target);
                        setImgUrl(element);
                    }
                }
            },
            { rootMargin: "0px 0px 100px 0px", threshold: [0.01] }
        );
    } else {
        // 绑定事件:
        $(window).scroll(lazyImageShow);
        console.log("Not Supported IntersectionObserver");
    }

    function addLazyImages(nodes) {
        nodes.each(function () {
            if (isSupportIntersectionObserver) {
                imgObserver.observe(this);
            } else {
                lazyImgs.push($(this));
            }
        });
        if (isSupportIntersectionObserver) {
            lazyImageShow();
        }
    }

    function domInsertedInit(event) {
        var nodeImg = $(event.target);
        var lazyImgages = nodeImg.find("img[data-src]");
        if (lazyImgages.length) {
            lazyImgages.each(function () {
                addLazyImages($(this));
            });
        }
    }

    // 未添加的元素监听img 加载
    document.addEventListener("DOMNodeInserted", domInsertedInit, false);

    //全局挂载
    window["lazyImageShow"] = lazyImageShow;
    window["lazyLoadImage"] = setImgUrl;
    window["addLazyImages"] = addLazyImages;
}
